//
//  HMRefreshControl.swift
//  微博
//
//  Created by 程双岐 on 16/9/25.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit

enum HMRefreshControlStrte {
    //下拉刷新
    case normal
    //释放刷新
    case pulling
    //正在刷新
    case refreshing
}

class HMRefreshControl: UIControl {

    var currentScrollView: UIScrollView?
    
    var hmState: HMRefreshControlStrte = .normal{
        didSet{
            switch hmState {
            case .normal:
                icomImage.isHidden = false
                indicatorView.stopAnimating()
                UIView.animate(withDuration: 0.25, animations: { 
                    self.icomImage.transform = CGAffineTransform.identity
                })
                
                if oldValue == .refreshing{
                    UIView.animate(withDuration: 0.25, animations: { 
                        self.currentScrollView?.contentInset.top -= 35
                    })
                }
                
                messageLabel.text = "下拉刷新"
                
            case .pulling:
                UIView.animate(withDuration: 0.25, animations: { 
                    self.icomImage.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
                })
                messageLabel.text = "松手就刷新"

            case .refreshing:
                icomImage.isHidden = true
                indicatorView.startAnimating()
                messageLabel.text = "正在刷新"
                
                UIView.animate(withDuration: 0.25, animations: {
                    self.currentScrollView?.contentInset.top += 35
                    
                })
                sendActions(for: .valueChanged)
            }
        }
    }
    
    private lazy var icomImage: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))

    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    
    private lazy var messageLabel:UILabel = {
        let label = UILabel()
        label.textColor = UIColor.darkGray
        label.font = UIFont.systemFont(ofSize: 12)
        label.numberOfLines = 0
        label.text = "下拉刷新"
        return label
    }()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)

        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
//        backgroundColor = UIColor.red
        addSubview(icomImage)
        addSubview(indicatorView)
        addSubview(messageLabel)
        
        icomImage.translatesAutoresizingMaskIntoConstraints = false
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        
        
        addConstraint(NSLayoutConstraint(item: icomImage, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: -35))
        
        addConstraint(NSLayoutConstraint(item: icomImage, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .leading, relatedBy: .equal, toItem: icomImage, attribute: .trailing, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .centerY, relatedBy: .equal, toItem: icomImage, attribute: .centerY, multiplier: 1, constant: 0))
        
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerX, relatedBy: .equal, toItem: icomImage, attribute: .centerX, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerY, relatedBy: .equal, toItem: icomImage, attribute: .centerY, multiplier: 1, constant: 0))
        
    }
    
    override func willMove(toSuperview newSuperview: UIView?) {
        
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }
        self.frame.size = CGSize(width: scrollView.frame.size.width, height: 35)
        self.frame.origin.y = -35
        
        
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
        
        currentScrollView = scrollView
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
//        print(currentScrollView?.contentOffset.y)
        
        let contenOffSetY = currentScrollView!.contentOffset.y
        
        let maxY = -(currentScrollView!.contentInset.top + 35)
        
        //怎么判断是在拖动状态
        
        if currentScrollView!.isDragging {
            
            if contenOffSetY < maxY && hmState == .normal {
                print("松手就刷新puling")
                hmState = .pulling
            }else if contenOffSetY >= maxY && hmState == .pulling {
                print("下拉刷新normal")
                hmState = .normal
            }
        }else{
            if hmState == .pulling {
                hmState = .refreshing
            }
        }
        
    }
    
    func endRefreshing(){
        hmState = .normal
    }
    
    deinit {
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
}
